#include "friendlogic.h"
#include"networkmanager.h"
#include"messageconst.h"

DEFINE_SINGLE_ATTRIBUTES(FriendLogic);

FriendLogic::FriendLogic()
{
    NET_INSTANCE()->add(MESSAGE_REJECT_FRIEND,handler(this,SEL_EVENTFUNC(FriendLogic::c2sRejectFriend)));
    NET_INSTANCE()->add(MESSAGE_DEL_FRIEND,handler(this,SEL_EVENTFUNC(FriendLogic::c2sDelFriend)));
    NET_INSTANCE()->add(MESSAGE_APPLY_FRIEND,handler(this,SEL_EVENTFUNC(FriendLogic::c2sApplyFriend)));
    NET_INSTANCE()->add(MESSAGE_AGREE_FRIEND,handler(this,SEL_EVENTFUNC(FriendLogic::c2sAgreeFriend)));
}

void FriendLogic::c2sApplyFriend(Json::Value& msg)
{
    int fd=NET_INSTANCE()->getFd();
    auto& playermaps=NET_SOCKET().m_playermaps;
    std::string rolename=msg["rolename"].asString();
    for(auto var:playermaps)
    {
        if(var.second.rolename==rolename)
        {
            auto info=playermaps[fd];
            msg.clear();
            msg["playername"]=info.playername;
            msg["rolename"]=info.rolename;
            msg["playertype"]=info.playertype;
            msg["grade"]=info.grade;
            NET_INSTANCE()->send(var.first,MESSAGE_APPLY_FRIEND,msg);
        }
    }
}

void FriendLogic::c2sAgreeFriend(Json::Value& msg)
{
    int fd=NET_INSTANCE()->getFd();
    auto& playermaps=NET_SOCKET().m_playermaps;
    std::string rolename=msg["rolename"].asString();
    for(auto var:playermaps)
    {
        if(var.second.rolename==rolename)
        {
            auto info=playermaps[fd];
            msg.clear();
            msg["playername"]=info.playername;
            msg["rolename"]=info.rolename;
            msg["playertype"]=info.playertype;
            msg["grade"]=info.grade;
            NET_INSTANCE()->send(var.first,MESSAGE_AGREE_FRIEND,msg);
        }
    }
}


void FriendLogic::c2sRejectFriend(Json::Value& msg)
{
    int fd=NET_INSTANCE()->getFd();
    auto& playermaps=NET_SOCKET().m_playermaps;
    std::string rolename=msg["rolename"].asString();
    for(auto var:playermaps)
    {
        if(var.second.rolename==rolename)
        {
            auto info=playermaps[fd];
            msg.clear();
            msg["playername"]=info.playername;
            msg["rolename"]=info.rolename;
            msg["playertype"]=info.playertype;
            msg["grade"]=info.grade;
            NET_INSTANCE()->send(var.first,MESSAGE_REJECT_FRIEND,msg);
        }
    }
}

void FriendLogic::c2sDelFriend(Json::Value& msg)
{
    int fd=NET_INSTANCE()->getFd();
    auto& playermaps=NET_SOCKET().m_playermaps;
    std::string rolename=msg["rolename"].asString();
    for(auto var:playermaps)
    {
        if(var.second.rolename==rolename)
        {
            auto info=playermaps[fd];
            msg.clear();
            msg["playername"]=info.playername;
            msg["rolename"]=info.rolename;
            msg["playertype"]=info.playertype;
            msg["grade"]=info.grade;
            NET_INSTANCE()->send(var.first,MESSAGE_DEL_FRIEND,msg);
        }
    }
}
